<?php
namespace app\client\wxpay;
include_once __DIR__ . '/wxpay/WxPay.Api.php';
/**
 * 统一下单对象
 * **/

class WxPayUnifiedOrder {
    private $input = null;
    private $config = null;
    
    public function __construct($openId) {
        $this->input = new \WxPayUnifiedOrder();
        $this->input->SetOpenid($openId);
        $this->input->SetTrade_type("JSAPI");
        
        $this->config = new \app\client\wxpay\Config();
    }
    
    public function setOrder($order) {
        //$order['amount'] = 0.01;
       $http = '';
        if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === "on"){
            $http = 'https';
        }
        //$order['notify_url'] = $http . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '/Notify/' . $order['notify_url'];
        
        $order['notify_url'] = 'https://r.kingwish.com.cn/api/notify/' . $order['notify_url'];
        
        $this->input->SetBody($order['body']);
        $this->input->SetOut_trade_no($order['order_no']);
        $this->input->SetTotal_fee($order['amount'] * 100);
        $this->input->SetNotify_url($order['notify_url']);
    }
    
    public function getParams() {
        $order = \WxPayApi::unifiedOrder($this->config, $this->input);
        $res = ['err' => 1];
        if($order['return_code'] !== 'SUCCESS'){
            $res['msg'] = $order['return_msg'];
            return $res;
        }else{
            if($order['result_code'] !== 'SUCCESS'){
                $res['msg'] = $order['err_code_des'];
                return $res;
            }
        }
        
        $res['err'] = 0;
        $res['params'] = $this->_getJsApiParameters($order, $this->config);
        
        return $res;
    }
    
    private function _getJsApiParameters($UnifiedOrderResult, $config) {
        if(!array_key_exists('appid', $UnifiedOrderResult)
            || !array_key_exists('prepay_id', $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == '')
        {
            throw new \WxPayException('参数错误');
        }
        
        $jsapi = new \WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult['appid']);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(\WxPayApi::getNonceStr());
        $jsapi->SetPackage('prepay_id=' . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetPaySign($jsapi->MakeSign($this->config));
        return $jsapi->GetValues();
    }
}